package edu.columbia.cloudbox.ui;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import edu.columbia.cloudbox.R;
import edu.columbia.cloudbox.UserStatusService;
import edu.columbia.cloudbox.io.LocalIO;
import edu.columbia.cloudbox.io.S3IO;

public class LoginActivity extends Activity {
	private Button login_login;
	private Button login_register;
	private EditText usernameText;
	private EditText passwordText;
	private AlertDialog progressDialog;

	/** Create view */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);

		login_login = (Button) findViewById(R.id.login_login);
		login_register = (Button) findViewById(R.id.login_register);
		usernameText = (EditText) findViewById(R.id.login_username);
		passwordText = (EditText) findViewById(R.id.login_password);

		// Set event listener to register button
		login_register.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent myIntent = new Intent();
				myIntent.setClass(LoginActivity.this,
						edu.columbia.cloudbox.ui.RegisterActivity.class);
				startActivity(myIntent);
			}
		});

		// Set event listener to login button
		login_login.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				String username = usernameText.getText().toString();
				String password = passwordText.getText().toString();
				new LoginTask().execute(username, password);
			}
		});
	}

	private boolean login(String username, String password) {
		boolean result = false;

		// send login to ec2 server
		String Login_Credential = "username=" + username + "&password="
				+ password;
		Log.i("login", Login_Credential);
		try {
			// Send data
			URL url = new URL("http://107.22.164.227:8080/ServletHost/login");
			URLConnection conn = url.openConnection();
			conn.setDoOutput(true);
			OutputStreamWriter wr = new OutputStreamWriter(
					conn.getOutputStream());
			wr.write(Login_Credential);
			wr.flush();

			// Get the response
			InputStream is = conn.getInputStream();

			int c;
			if ((c = is.read()) != -1) {
				result = true;

				UserStatusService.USER_NAME = username;
				UserStatusService.USER_LOGGED_IN = true;
				UserStatusService.S3IO_INSTANCE = new S3IO(is,
						LoginActivity.this);
				UserStatusService.LocalIO_INSTANCE = new LocalIO(username,
						LoginActivity.this);
				UserStatusService.initialize(LoginActivity.this);

				Intent myIntent = new Intent();
				myIntent.setClass(LoginActivity.this,
						edu.columbia.cloudbox.CloudBoxActivity.class);
				startActivity(myIntent);

			} else {
				result = false;
			}

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	private class LoginTask extends AsyncTask<String, Void, Boolean> {

		@Override
		protected void onPreExecute() {
			Log.i("LoginActivity", "in onPreExecute()");
			progressDialog = ProgressDialog.show(LoginActivity.this, "",
					"Logging in!", true);
		}

		@Override
		protected Boolean doInBackground(String... params) {
			Log.i("LoginActivity", "in doInBackground(Void... params)");
			boolean success = login(params[0], params[1]);
			return success;
		}

		@Override
		protected void onPostExecute(Boolean success) {
			Log.i("LoginActivity", "onPostExecute(" + success + ")");
			progressDialog.dismiss();
			if (!success) {
				progressDialog = Notifications.infoDialog(LoginActivity.this,
						"Login failed!", "Username or pasword wrong!");
				new Handler().postDelayed(new Runnable() {
					@Override
					public void run() {
						Log.i("Handler", "dismiss");
						progressDialog.dismiss();
					}
				}, 3000);
			}

		}
	}
}
